package com.ylr.base.common.jsr303.validator;



import com.ylr.base.common.jsr303.annotation.ListString;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wei
 * date: 2023-04-05 16:45:37
 * className: ListStringValidator 字符串列表枚举值校验逻辑类
 * version: 1.0
 * description:
 */
public class ListStringValidator implements ConstraintValidator<ListString, List<String>> {

    private String[] enumValues;

    @Override
    public void initialize(ListString constraintAnnotation) {
        enumValues = constraintAnnotation.enumValues();
        Arrays.sort(enumValues);
    }

    @Override
    public boolean isValid(List<String> valueList, ConstraintValidatorContext context) {
        if (Objects.isNull(valueList)) {
            return false;
        }
        for (String value : valueList) {
            if (Objects.isNull(value)) {
                return false;
            }
            if (this.binarySearchFail(value)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 二分查找判断参数值是否再数组中
     * @param value 参数值
     * @return true-不在 false-在
     */
    private boolean binarySearchFail(String value) {
        if (enumValues.length == 0) {
            // 没有枚举值，直接返回成功
            return false;
        }
        int lo = 0, hi = enumValues.length - 1;
        while (lo <= hi) {
            int mid = (lo + hi) >> 1;
            int res = enumValues[mid].compareTo(value);
            if (res > 0) {
                hi = mid - 1;
            } else if (res < 0) {
                lo = mid + 1;
            } else {
                // 找到
                return false;
            }
        }
        // 未找到
        return true;
    }
}
